package mi.payment.utils.transaction;

import android.content.Context;

import java.util.Map;

import mi.payment.bean.db.TradeData;
import mi.payment.constants.TransactionBitmap;
import mi.payment.utils.iso8583.EncodePackage;
import mi.payment.utils.iso8583.FieldConfig;
import mi.payment.utils.iso8583.FieldUtils;
import mi.payment.utils.iso8583.MsgField;
import mi.payment.utils.secure.TerminalSecure;

/**
 * 电子签名上送
 *
 * @author tomcat on 2017/2/17.
 */

public class ESignUploadTask extends TransactionTask<TradeData, Void, TradeData> {

    public ESignUploadTask(Context c) {
        super(c, false);
    }

    @Override
    protected void onBegin(TradeData[] params) {
        tradeData = params[0];
        dbBean = tradeData.getPayDetail();
    }

    @Override
    protected TradeData appointResult() {
        mPayDetailModel.updateESignIsUploaded(dbBean);
        return tradeData;
    }

    @Override
    protected Map<String, MsgField> preAssembly() {
        return EncodePackage.preAssemblyBase(TransactionBitmap.BITMAP_ELECTRONIC_SIGNATURE_UPLOAD);
    }

    @Override
    protected byte[] changeAndAssembly(Map<String, MsgField> fieldMap) {
        dbBean.setProcessCode("000000");
        dbBean.setTransType("07");
        dbBean.setNetManageCode("800");
        dbBean.TerminalDate = System.currentTimeMillis() / 1000;
        dbBean.isNeedReversal = false;
        dbBean.tradeAnswerCode = "96";

        // 赋值原交易参考号
        dbBean.setOriginalReferNo(dbBean.getReferNo());

        // 更新预组装的Map
        Map<String, MsgField> map = FieldUtils.fillEachFieldValue(fieldMap, tradeData);

        // 60域
        MsgField fieldF060 = map.get("F060");
        String value60 = dbBean.getTransType() + dbBean.getBathNo() + dbBean.getNetManageCode();
        fieldF060.setDataStr(value60);

        // 62域
        MsgField f062 = fieldMap.get("F062");
        f062.setDataType(FieldConfig.SDK_8583_DATA_BIT);
        f062.setDataStr(dbBean.eSignHexData);

        // 组包,得到组包后的报文
        return EncodePackage.assembly(map, "0820", TerminalSecure.PROCESSREQUEST_NONE);
    }

}
